# encoding:utf-8
from django.shortcuts import render
from django.views.generic.base import View
from django.http import HttpResponse
from django.db.models import Q

from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from .models import Course, CourseResource, Video
from operation.models import UserFavorite, CourseComments, UserCourse
from utils.mixin_utils import LoginRequiredMixin

# Create your views here.


class CourseListView(View):
    def get(self, request):
        all_courses = Course.objects.all().order_by('-add_time')  # 默认按时间排序

        # 课程搜索
        search_keywords = request.GET.get('keywords', '')
        if search_keywords:
            all_courses = all_courses.filter(Q(name__contains=search_keywords)|Q(desc__contains=search_keywords)|Q(detail__contains=search_keywords))

        # 课程排序
        sort = request.GET.get('sort', '')
        if sort:
            if sort == 'students':
                all_courses = all_courses.order_by('-students')
            elif sort == 'hot':
                all_courses = all_courses.order_by('-click_nums')

        hot_courses = Course.objects.all().order_by('-click_nums')[:3]

        # 对课程进行分页
        try:
            page = request.GET.get('page', 1)  # 生成页码会自动加上page
        except PageNotAnInteger:
            page = 1

        p = Paginator(all_courses, 6, request=request)
        courses = p.page(page)

        return render(request, 'course-list.html', {
            'all_courses': courses,
            'sort': sort,
            'hot_courses': hot_courses,
        })

class VideoPlayView(View):
    """
    视频播放页面
    """
    def get(self, request, video_id):
        video = Video.objects.get(id=int(video_id))
        course = video.lesson.course
        course.students += 1
        course.save()
        #查询用户是否已经关联了该课程
        user_courses = UserCourse.objects.filter(user=request.user, course=course)
        if not user_courses:
            user_course = UserCourse(user=request.user,course=course)
            user_course.save()

        # 学过该课程的同学还学过什么课程功能:
        # 1.找出学过该课程的用户id
        # 2.根据用户id查询课程id
        # 3.根据课程id查出相关课程，并按点击数排序
        user_courses = UserCourse.objects.filter(course=course)
        # user_ids = [user_course.user.id for user_course in user_courses]
        user_ids = [user_course.user.id for user_course in user_courses]         # 获取学过该课程的用户id
        all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)    # 获取这些用户的用户课程queryset，user_id 直接取user字段的值，这里不用传user实例进来
        # course_ids = [user_course.course.id for user_course in all_user_courses]
        # relate_courses = Course.objects.filter(id__in=course_ids).order_by('-click_nums')
        # 疑问？ all_user_courses 和 relate_courses有什么不同吗？
        # all_user_courses对象是针对UserCourse表，relate_courses针对Course表，传递relate_course对象给前端方便处理

        all_resources = CourseResource.objects.filter(course=course)
        return render(request, 'course-play.html', {
            'course': course,
            'course_resources': all_resources,
            'relate_courses': all_user_courses,
            'video': video,
        })



class CourseDetailView(View):
    """
    课程详情页
    """

    def get(self, request, course_id):
        course = Course.objects.get(id=int(course_id))
        # 点击后，click_nums加1，增加课程点击数
        course.click_nums += 1
        course.save()

        has_fav_course = False
        has_fav_org = False

        if request.user.is_authenticated():
            if UserFavorite.objects.filter(user=request.user, fav_id=course_id, fav_type=1):
                has_fav_course = True
            if UserFavorite.objects.filter(user=request.user, fav_id=course.course_org.id, fav_type=2):
                has_fav_org = True

        tag = course.tag
        if tag:
            relate_courses = Course.objects.filter(tag=tag)[:2]
        else:
            relate_courses = []  # None 传入template中循环会出错
        return render(request, 'course-detail.html', {
            'course': course,
            'relate_courses': relate_courses,
            'has_fav_course': has_fav_course,
            'has_fav_org': has_fav_org,
        })


class CourseInfoView(LoginRequiredMixin, View):
    """
    课程章节信息
    """

    def get(self, request, course_id):
        course = Course.objects.get(id=int(course_id))
        course.students += 1
        course.save()

        #查询用户是否已经关联了该课程
        user_courses = UserCourse.objects.filter(user=request.user, course=course)
        if not user_courses:
            user_course = UserCourse(user=request.user,course=course)
            user_course.save()

        # 学过该课程的同学还学过什么课程功能:
        # 1.找出学过该课程的用户id
        # 2.根据用户id查询课程id
        # 3.根据课程id查出相关课程，并按点击数排序
        user_courses = UserCourse.objects.filter(course=course)
        # user_ids = [user_course.user.id for user_course in user_courses]
        user_ids = [user_course.user.id for user_course in user_courses]         # 获取学过该课程的用户id
        all_user_courses = UserCourse.objects.filter(user_id__in=user_ids)    # 获取这些用户的用户课程queryset，user_id 直接取user字段的值，这里不用传user实例进来
        # course_ids = [user_course.course.id for user_course in all_user_courses]
        # relate_courses = Course.objects.filter(id__in=course_ids).order_by('-click_nums')
        # 疑问？ all_user_courses 和 relate_courses有什么不同吗？
        # all_user_courses对象是针对UserCourse表，relate_courses针对Course表，传递relate_course对象给前端方便处理

        all_resources = CourseResource.objects.filter(course=course)
        return render(request, 'course-video.html', {
            'course': course,
            'course_resources': all_resources,
            'relate_courses': all_user_courses,
        })


class CommentsView(LoginRequiredMixin, View):
    def get(self, request, course_id):
        course = Course.objects.get(id=int(course_id))
        all_resources = CourseResource.objects.filter(course=course)
        # all_comments = CourseComments.objects.all()
        comments = CourseComments.objects.filter(course_id=course_id)  # 只展示对应课程ID的评论
        return render(request, 'course-comment.html', {
            'course': course,
            'course_resources': all_resources,
            'all_comments': comments,
        })


class AddCommentView(View):
    """
    用户添加课程评论
    """

    def post(self, request):
        # 先判断用户是否登录
        if not request.user.is_authenticated():
            return HttpResponse('{"status":"fail", "msg":"用户未登录"}', content_type='application/json')

        course_id = request.POST.get('course_id', 0)
        comments = request.POST.get('comments', "")
        if course_id > 0 and comments:
            course_comments = CourseComments()
            course = Course.objects.get(id=int(course_id))
            course_comments.course = course  # 这里必须传递对象，如传递int则： "CourseComments.course" must be a "Course" instance
            course_comments.comments = comments
            course_comments.user = request.user
            course_comments.save()
            return HttpResponse('{"status":"success", "msg":"添加成功"}', content_type='application/json')
        else:
            return HttpResponse('{"status":"fail", "msg":"添加失败"}', content_type='application/json')
